<!-- 注册页面 -->
<template>
  <div class="register-container">
    <el-card class="register-card">
      <h2 class="register-title">账号注册</h2>
      <el-tabs v-model="activeRole" class="role-tabs" @tab-change="handleRoleChange">
        <el-tab-pane label="超级管理员" name="super_admin" :disabled="true"></el-tab-pane>
        <el-tab-pane label="商家" name="merchant"></el-tab-pane>
        <el-tab-pane label="医生" name="doctor"></el-tab-pane>
      </el-tabs>
      <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="100px"
        class="register-form">
        <el-form-item label="账号" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" type="email" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <!-- 商家额外字段 -->
        <template v-if="activeRole === 'merchant'">
          <el-form-item label="商家名称" prop="merchantName">
            <el-input v-model="registerForm.merchantName" placeholder="请输入商家名称"></el-input>
          </el-form-item>
          <el-form-item label="营业执照" prop="businessLicense">
            <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleLicenseUpload"
              :before-upload="handleBeforeUpload" :file-list="licenseFileList" list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="所属地区" prop="region">
            <el-cascader v-model="registerForm.region" :options="regionOptions" placeholder="请选择地区"
              @change="handleRegionChange"></el-cascader>
          </el-form-item>
        </template>

        <!-- 医生额外字段 -->
        <template v-if="activeRole === 'doctor'">
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="registerForm.realName" placeholder="请输入真实姓名"></el-input>
          </el-form-item>
          <el-form-item label="所属医院" prop="hospitalId">
            <el-select v-model="registerForm.hospitalId" placeholder="请选择所属医院">
              <el-option v-for="item in hospitalList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="专业领域" prop="specialty">
            <el-input v-model="registerForm.specialty" placeholder="请输入专业领域（如：宠物外科）"></el-input>
          </el-form-item>
          <el-form-item label="执业证书" prop="certificate">
            <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleCertificateUpload"
              :before-upload="handleBeforeUpload" :file-list="certificateFileList" list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </template>

        <el-form-item label="验证码" prop="code">
          <div class="code-container">
            <el-input v-model="registerForm.code" placeholder="请输入验证码"></el-input>
            <el-button type="text" @click="sendCode" :disabled="codeDisabled">
              {{ codeText }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="registerForm.agreement">同意<a href="#" class="agreement-link">用户协议</a>和<a href="#"
              class="agreement-link">隐私政策</a></el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" class="register-btn" :loading="loading">
            注册
          </el-button>
          <router-link to="/login" class="login-link">已有账号？去登录</router-link>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { register } from '../../api/auth'
import { getHospitalList } from '../../api/hospital'
import { ElMessage } from 'element-plus'

const router = useRouter()
const registerFormRef = ref(null)
const loading = ref(false)
const activeRole = ref('merchant')
const uploadUrl = import.meta.env.VITE_UPLOAD_URL || '/api/upload'

// 倒计时相关
const codeDisabled = ref(false)
const codeText = ref('获取验证码')
let countdownTimer = null

// 文件列表
const licenseFileList = ref([])
const certificateFileList = ref([])

// 地区选择数据（模拟）
const regionOptions = ref([
  {
    value: 'beijing',
    label: '北京',
    children: [
      { value: 'beijing', label: '北京市' },
      { value: 'haidian', label: '海淀区' }
    ]
  },
  {
    value: 'shanghai',
    label: '上海',
    children: [
      { value: 'shanghai', label: '上海市' },
      { value: 'pudong', label: '浦东新区' }
    ]
  }
])

// 医院列表
const hospitalList = ref([])

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  code: '',
  agreement: false,
  // 商家字段
  merchantName: '',
  businessLicense: '',
  region: [],
  // 医生字段
  realName: '',
  hospitalId: '',
  specialty: '',
  certificate: ''
})

// 表单校验规则
const registerRules = computed(() => ({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 20, message: '账号长度在4-20位之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  agreement: [
    {
      required: true, validator: (rule, value, callback) => {
        value ? callback() : callback(new Error('请同意用户协议和隐私政策'))
      }, trigger: 'change'
    }
  ],
  // 商家额外校验
  ...(activeRole.value === 'merchant' && {
    merchantName: [
      { required: true, message: '请输入商家名称', trigger: 'blur' }
    ],
    businessLicense: [
      { required: true, message: '请上传营业执照', trigger: 'change' }
    ],
    region: [
      { required: true, message: '请选择地区', trigger: 'change' }
    ]
  }),
  // 医生额外校验
  ...(activeRole.value === 'doctor' && {
    realName: [
      { required: true, message: '请输入真实姓名', trigger: 'blur' }
    ],
    hospitalId: [
      { required: true, message: '请选择所属医院', trigger: 'change' }
    ],
    specialty: [
      { required: true, message: '请输入专业领域', trigger: 'blur' }
    ],
    certificate: [
      { required: true, message: '请上传执业证书', trigger: 'change' }
    ]
  })
}))

// 发送验证码
const sendCode = () => {
  // 简单校验手机号
  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(registerForm.phone)) {
    ElMessage.error('请输入正确的手机号')
    return
  }

  // 模拟发送验证码
  codeDisabled.value = true
  let countdown = 60
  codeText.value = `${countdown}秒后重新获取`

  countdownTimer = setInterval(() => {
    countdown--
    codeText.value = `${countdown}秒后重新获取`
    if (countdown <= 0) {
      clearInterval(countdownTimer)
      codeDisabled.value = false
      codeText.value = '获取验证码'
    }
  }, 1000)

  // 实际项目中调用发送验证码接口
  console.log('发送验证码到:', registerForm.phone)
}

// 切换角色
const handleRoleChange = (role) => {
  activeRole.value = role
  // 医生角色需要获取医院列表
  if (role === 'doctor') {
    fetchHospitalList()
  }
}

// 获取医院列表
const fetchHospitalList = async () => {
  try {
    const res = await getHospitalList()
    hospitalList.value = res.data
  } catch (error) {
    ElMessage.error('获取医院列表失败')
  }
}

// 营业执照上传成功
const handleLicenseUpload = (response) => {
  registerForm.businessLicense = response.data.url
  licenseFileList.value = [{ url: response.data.url }]
}

// 执业证书上传成功
const handleCertificateUpload = (response) => {
  registerForm.certificate = response.data.url
  certificateFileList.value = [{ url: response.data.url }]
}

// 上传前校验
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片文件')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  return true
}

// 地区选择改变
const handleRegionChange = (value) => {
  registerForm.region = value
}

// 注册提交
const handleRegister = async () => {
  try {
    await registerFormRef.value.validate()
    loading.value = true

    // 构造注册数据
    const registerData = {
      username: registerForm.username,
      password: registerForm.password,
      phone: registerForm.phone,
      email: registerForm.email,
      role: activeRole.value,
      ...(activeRole.value === 'merchant' && {
        merchantName: registerForm.merchantName,
        businessLicense: registerForm.businessLicense,
        region: registerForm.region.join('/')
      }),
      ...(activeRole.value === 'doctor' && {
        realName: registerForm.realName,
        hospitalId: registerForm.hospitalId,
        specialty: registerForm.specialty,
        certificate: registerForm.certificate
      })
    }

    // 调用注册接口
    await register(registerData)
    ElMessage.success('注册成功，请登录')
    router.push('/login')
  } catch (error) {
    ElMessage.error(error.message || '注册失败，请重试')
  } finally {
    loading.value = false
  }
}

// 页面卸载时清除定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})

// 页面挂载时初始化
onMounted(() => {
  // 默认加载医生所需的医院列表
  if (activeRole.value === 'doctor') {
    fetchHospitalList()
  }
})
</script>

<style scoped lang="scss">
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;

  .register-card {
    width: 550px;
    padding: 30px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .register-title {
      text-align: center;
      margin-bottom: 20px;
      color: #1989fa;
      font-size: 20px;
      font-weight: 600;
    }

    .role-tabs {
      margin-bottom: 20px;
    }

    .register-form {
      .code-container {
        display: flex;
        gap: 10px;

        .el-input {
          flex: 1;
        }
      }

      .agreement-link {
        color: #1989fa;
        text-decoration: none;
        margin: 0 4px;
      }

      .register-btn {
        width: 100%;
        margin-bottom: 10px;
      }

      .login-link {
        display: block;
        text-align: center;
        color: #1989fa;
        text-decoration: none;
      }
    }
  }
}

::v-deep .el-upload--picture-card {
  width: 120px;
  height: 120px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
}
</style>